package com.qq.BFMRSE.BF_MRSEController;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;

import com.qq.BFMRSE.Module.upLoadTool;
import com.qq.BFMRSE.controllerHelper.newIndexHelper;
import com.qq.BFMRSE.model.indexTree;
import com.qq.BFMRSE.model.indexTreeNode;
import com.qq.BFMRSE.util.BFConstants;
import com.qq.BFMRSE.util.paraseJsonUtil;

import net.sf.json.JSONObject;

@Controller
public class handlerNewIndex {
	@RequestMapping(value= "/newIndexTree",method=RequestMethod.POST)
	public void handler(HttpServletRequest request,HttpServletResponse response){
		 response.setContentType("text/html;charset=utf-8");
	     response.setCharacterEncoding("utf-8");
			Logger log=Logger.getLogger(handlerNewEncryIndex.class);
	     String userName=request.getParameter("userName");
	     String indexTreeInfo=request.getParameter("indexTreeInfo");
	     String levelBitInfo=request.getParameter("levelBitInfo");
	     JSONObject rootJO=JSONObject.fromObject(indexTreeInfo);    
	     indexTreeNode root=(indexTreeNode) rootJO.toBean(rootJO, indexTreeNode.class);
	     indexTree tree=new indexTree(root);
	     List<indexTreeNode>leafNodes=tree.getAllLeafNode(tree.getRoot());
	     Map<String,List<Integer>> bitSetInfoMap=paraseJsonUtil.Json2MapBitSet(levelBitInfo);
	     newIndexHelper.updateLeafBit(leafNodes, bitSetInfoMap);
	     newIndexHelper.updateInteralNodeBit(tree);
	     tree.setAllNodeParent(tree.getRoot());
	     String tmpDir=ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/")+"tmp";
	     File tmpFile=new File(tmpDir);
	     if(!tmpFile.exists()||!tmpFile.isDirectory()){
	    	 tmpFile.mkdir();
	     }
	     upLoadTool ut=new upLoadTool(userName, BFConstants.UPENCRYPTTREE, tmpDir);
	     ut.upLoadToHdfs(root);
			log.info("User:"+userName+" upload index tree.");
	     PrintWriter out = null;  
		    try {  
		        out = response.getWriter();  
		        out.append("success");  
		    } catch (IOException e) {  
		        e.printStackTrace();  
		    } finally {  
		        if (out != null) {  
		        	out.flush();
		            out.close();  
		        }  
		    }  	    
	}
}
